<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'

import { useRoute, useRouter } from 'vue-router'
import Foot from './components/Foot.vue'
import Message from './components/Message.vue'

const router = useRouter()
const route = useRoute()
const messageRef = ref()
const qrCodeContent = ref('')
const showQRCodeDialog = ref(false)
let scanBuffer = ''
let scanTimer: any = null
let isRequesting = false  // 添加请求状态标记

// 动态缓存控制
const cachedComponents = ref<string[]>([])
let lastRoute = ''

// 主题配置
const themeOptions = [
  {
    value: 'blue',
    name: '蓝色主题',
    primary: '#158ac0',
    secondary: '#5cc2e6'
  },
  {
    value: 'green', 
    name: '绿色主题',
    primary: '#10b981',
    secondary: '#34d399'
  },
  {
    value: 'purple',
    name: '紫色主题', 
    primary: '#7c3aed',
    secondary: '#a78bfa'
  }
]

// 应用主题
const applyTheme = (theme:any) => {
  const selectedTheme = themeOptions.find(t => t.value === theme)
  if (selectedTheme) {
    // 设置CSS变量来应用主题色
    document.documentElement.style.setProperty('--theme-primary', selectedTheme.primary)
    document.documentElement.style.setProperty('--theme-secondary', selectedTheme.secondary)
    
    // 设置hover状态的颜色（稍微深一点的颜色）
    const primaryHover = adjustBrightness(selectedTheme.primary, -0.2)
    const secondaryHover = adjustBrightness(selectedTheme.secondary, -0.15)
    document.documentElement.style.setProperty('--theme-primary-hover', primaryHover)
    document.documentElement.style.setProperty('--theme-secondary-hover', secondaryHover)
    
    // 通知其他组件主题变化
    window.dispatchEvent(new CustomEvent('theme-changed', { 
      detail: { theme: theme, colors: selectedTheme } 
    }))
  }
}

// 调整颜色亮度的辅助函数
const adjustBrightness = (hexColor:any, factor:any) => {
  // 移除#号
  const hex = hexColor.replace('#', '')
  
  // 转换为RGB
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 调整亮度
  const newR = Math.max(0, Math.min(255, Math.round(r * (1 + factor))))
  const newG = Math.max(0, Math.min(255, Math.round(g * (1 + factor))))
  const newB = Math.max(0, Math.min(255, Math.round(b * (1 + factor))))
  
  // 转换回十六进制
  return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`
}

// 初始化主题
const initTheme = () => {
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    console.log('应用启动时从localStorage获取主题:', savedTheme)
    applyTheme(savedTheme)
  } else {
    // 如果没有保存的主题，应用默认的蓝色主题
    console.log('应用启动时使用默认蓝色主题')
    applyTheme('blue')
  }
}

// 监听路由变化来动态控制缓存
watch(() => route.path, (newPath, oldPath) => {
  console.log('Route changed:', { from: oldPath, to: newPath })
  
  // 如果是从 tableGame 或 table 页面返回到 report 页面，则缓存 report
  if ((oldPath === '/tableGame' || oldPath === '/table') && newPath === '/report') {
    if (!cachedComponents.value.includes('report')) {
      cachedComponents.value.push('report')
      console.log('Added report to cache')
    }
  } 
  // 如果是从 report 页面离开到其他页面（除了 tableGame 和 table），则清除缓存
  else if (oldPath === '/report' && newPath !== '/tableGame' && newPath !== '/table') {
    cachedComponents.value = cachedComponents.value.filter(name => name !== 'report')
    console.log('Removed report from cache')
  }
  // 如果直接进入 report 页面，也缓存它
  else if (newPath === '/report' && !cachedComponents.value.includes('report')) {
    cachedComponents.value.push('report')
    console.log('Added report to cache (direct access)')
  }
  
  lastRoute = oldPath || ''
}, { immediate: true })

onMounted(() => {
  // 初始化主题
  initTheme()
  
  window.messageRef = messageRef.value
  // 监听扫码盒子输入
  window.addEventListener('keydown', handleQRCodeInput)
})

function handleQRCodeInput(e: KeyboardEvent) {
  console.log(e);
  
  // 只收集可见字符
  if (e.key.length === 1) {
    scanBuffer += e.key
    if (scanTimer) clearTimeout(scanTimer)
    scanTimer = setTimeout(() => { 
      scanBuffer = '' 
      isRequesting = false  // 重置请求状态
    }, 500)
  }
  // 回车时判定为扫码结束
  if (e.key === 'Enter' && scanBuffer && !isRequesting) {
    isRequesting = true  // 标记正在请求
    showQRCodeDialog.value = true
    qrCodeContent.value = scanBuffer
    scanBuffer = ''

    window.request?.('/system/patient/scanCode/'+qrCodeContent.value, { method: 'GET',params:{
      codeKey:qrCodeContent.value
    } }).then(res => {
      console.log(res);
      if (res) {
        isRequesting = false  // 请求失败也要重置状态
        localStorage.setItem('user',JSON.stringify(res))
          // 触发自定义事件，通知其他页面更新缓存
          window.dispatchEvent(new CustomEvent('user-changed', { detail: res }))
          localStorage.removeItem('taskId')

          window.messageRef?.show('已切换到用户<' + res.name + '>', 'success')

      } else { 
        window.messageRef?.show('用户不存在', 'error')

      }
     
    }).catch(() => {
      isRequesting = false  // 请求失败也要重置状态
      window.messageRef?.show('用户不存在', 'error')

    })










    window.request?.('/system/patient/scanCode', { method: 'GET',params:{
      codeKey: qrCodeContent.value,
      
    } }).then(res => {
      console.log(res);
      
    })


    // getSysIpsList().then((res: any) => {



      
    //   console.log(res);
    //   console.log(res.data[0].ip);
    //   getUserList(res.data[0].ip,qrCodeContent.value).then((res2: any) => {
    //     console.log(res2);
    //     if (res2.data) {
    //       localStorage.setItem('user', JSON.stringify(res2.data))
    //       // 触发自定义事件，通知其他页面更新缓存
    //       window.dispatchEvent(new CustomEvent('user-changed', { detail: res2.data }))

    //       window.messageRef?.show('已切换到用户<' + res2.data.name + '>', 'success')

    //     } else { 
    //       window.messageRef?.show('用户不存在', 'error')
    //     }
    //     isRequesting = false  // 请求完成
     
    //   }).catch(() => {
    //     isRequesting = false  // 请求失败也要重置状态
    //   })
    // }).catch(() => {
    //   isRequesting = false  // 请求失败也要重置状态
    // })
    
    if (scanTimer) { 
      clearTimeout(scanTimer)
    }
  }
}

const apiErrorDialog = reactive({
  show: false,
  msg: '',
  callback: null as null | (() => void)
})

function handleApiErrorDialogClose() {
  apiErrorDialog.show = false
  if (typeof apiErrorDialog.callback === 'function') {
    apiErrorDialog.callback()
  } else {
    router.push({ path: '/' })
  }
  apiErrorDialog.callback = null
}

onMounted(() => {
  window.showApiErrorDialog = (msg: string, callback?: () => void) => {
    apiErrorDialog.show = true
    apiErrorDialog.msg = msg
    apiErrorDialog.callback = callback || null
  }
})
</script>

<template>
 
  <div class="app-bg">
    <router-view v-slot="{ Component, route }">
      <keep-alive :include="cachedComponents">
        <component :is="Component" :key="route.path" />
      </keep-alive>
    </router-view>
  </div>
  <Message ref="messageRef" />
  <Foot  v-if="route.path !== '/login'&&route.path !== '/echarts'&&route.path !== '/game'&&route.path !== '/table'&&route.path !== '/webView'&&route.path !== '/tableGame'" />
  
  <!-- 二维码弹窗 -->
  <!-- <div v-if="showQRCodeDialog" class="qr-dialog">
    <div class="qr-content">
      <h3>扫描结果</h3>
      <p>{{ qrCodeContent }}</p>
      <button @click="showQRCodeDialog = false">关闭</button>
    </div>
  </div> -->
  <!-- 自绘API错误弹窗 -->
  <div v-if="apiErrorDialog.show" class="custom-api-error-mask">
    <div class="custom-api-error-dialog">
      <div class="custom-api-error-title">提示</div>
      <div class="custom-api-error-content">{{ apiErrorDialog.msg }}</div>
      <div class="custom-api-error-footer">
        <button class="custom-api-error-btn" @click="handleApiErrorDialogClose">确定</button>
      </div>
    </div>
  </div>
</template>

<style>
.app-bg{
  background-color: var(--theme-secondary);
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo.electron:hover {
  filter: drop-shadow(0 0 2em #9FEAF9);
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}

.qr-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.qr-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}
.custom-api-error-mask {
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-api-error-dialog {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(33, 118, 184, 0.18);
  min-width: 320px;
  max-width: 80vw;
  padding: 0 0 18px 0;
  animation: popin 0.2s;
}
@keyframes popin {
  from { transform: scale(0.9); opacity: 0.5; }
  to   { transform: scale(1); opacity: 1; }
}
.custom-api-error-title {
  font-size: 18px;
  font-weight: bold;
  color: #2176b8;
  padding: 18px 24px 0 24px;
  text-align: left;
}
.custom-api-error-content {
  font-size: 15px;
  color: #333;
  padding: 18px 24px 0 24px;
  min-height: 40px;
  word-break: break-all;
}
.custom-api-error-footer {
  text-align: right;
  padding: 18px 24px 0 24px;
}
.custom-api-error-btn {
  background: linear-gradient(90deg, #2176b8 60%, #4caf50 100%);
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  padding: 7px 32px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(33, 118, 184, 0.08);
  transition: background 0.2s;
}
.custom-api-error-btn:hover {
  background: linear-gradient(90deg, #4caf50 60%, #2176b8 100%);
}
</style>
